import * as echarts from 'echarts'

export interface ChartStrategy {
  getOptions: () => echarts.EChartsOption
}

export function useECharts(
  chartRef: Ref<HTMLElement | null>,
  initOptions: echarts.EChartsOption,
  theme?: string | object | null,
  opts?: echarts.EChartsInitOpts
) {
  const chartInstance = shallowRef<echarts.EChartsType | null>(null)

  const options = reactive<echarts.EChartsOption>(
    initOptions as echarts.EChartsOption
  )

  const initChart = () => {
    if (chartRef.value && !chartInstance.value) {
      chartInstance.value = echarts.init(chartRef.value, theme, opts)
      chartInstance.value.setOption(options)
    }
  }

  const updateChartOptions = (newOptions: echarts.EChartsOption) => {
    if (chartInstance.value) {
      chartInstance.value.setOption(newOptions, {
        notMerge: true,
        lazyUpdate: true
      })
    }
  }

  const handleResize = () => {
    chartInstance.value?.resize()
  }

  const disposeChart = () => {
    chartInstance.value?.dispose()
    chartInstance.value = null
  }

  watch(options as echarts.EChartsOption, updateChartOptions, { deep: true })

  onMounted(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    disposeChart()
  })

  onActivated(() => {
    if (!chartInstance.value) {
      initChart()
    }
    window.addEventListener('resize', handleResize)
  })

  onDeactivated(() => {
    window.removeEventListener('resize', handleResize)
    disposeChart()
  })

  // 下载图表为图片
  const downloadChartImage: () => any = (filename = 'chart.png') => {
    if (chartInstance.value) {
      const base64 = chartInstance.value.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#fff'
      })
      const link = document.createElement('a')
      link.href = base64
      link.download = filename
      link.click()
    }
  }

  return {
    chartInstance,
    options,
    initChart,
    handleResize,
    disposeChart,
    downloadChartImage
  }
}
